package com.junpuxin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.junpuxin.dto.*;
import com.junpuxin.entity.Direction;
import com.junpuxin.excel.DirectionExcel;
import com.junpuxin.exception.IllegalParamException;
import com.junpuxin.exception.ServerErrorException;
import com.junpuxin.exception.VersionException;
import com.junpuxin.mapper.DirectionMapper;
import com.junpuxin.service.DirectionService;
import com.junpuxin.vo.DirectionVO;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author junpuxin
 */
@Service
@CacheConfig(cacheNames = "menu")
public class DirectionServiceImpl implements DirectionService {

    @Resource
    private DirectionMapper directionMapper;

    @CacheEvict(allEntries = true)
    @Override
    public int insert(DirectionInsertDTO dto) {
        String info = dto.getInfo();
        // 拷贝属性
        Direction direction = BeanUtil.copyProperties(dto, Direction.class);

        // 设置默认值
        direction.setVersion(0L);
        direction.setDeleted(0);
        direction.setInfo(StrUtil.isBlank(info) ? "暂无描述" : info);
        direction.setCreated(LocalDateTime.now());
        direction.setUpdated(LocalDateTime.now());
        // DB添加
        int result = directionMapper.insert(direction);
        if (result < 0) {
            throw new ServerErrorException("DB添加失败");
        }
        return result;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Direction select(Long id) {
        // DB查询
        Direction result = directionMapper.select(id);
        if(ObjectUtil.isNull(result)) {
            throw new ServerErrorException("记录不存在");
        }
        return result;
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<DirectionVO> list() {
        return directionMapper.list(new DirectionPageDTO())
                .stream()
                .map(direction -> BeanUtil.copyProperties(direction, DirectionVO.class))
                .collect(Collectors.toList());
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
                condition = "#p0 != null",
                unless = "#result == null")
    @Override
    public PageInfo<Direction> page(DirectionPageDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo<>(directionMapper.list(dto));
    }

    @CacheEvict(allEntries = true)
    @Transactional
    @Retryable(retryFor = VersionException.class)
    @Override
    public int update(DirectionUpdateDTO dto) {
        Long id = dto.getId();
        if(ObjectUtil.isNull(id)) {
            throw new IllegalParamException("ID为空");
        }
        Direction direction = directionMapper.select(id);
        if(ObjectUtil.isNull(direction)) {
            throw new ServerErrorException("记录不存在");
        }
        BeanUtil.copyProperties(dto, direction);
        // 设置默认值
        direction.setUpdated(LocalDateTime.now());
        // DB修改
        int result = directionMapper.update(direction);
        if (result <= 0) {
            throw new VersionException("DB修改失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int delete(Long id) {
        int result = directionMapper.delete(id);
        if (result <= 0) {
            throw new ServerErrorException("DB删除失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int deleteBatch(List<Long> ids) {
        int result = directionMapper.deleteBatch(ids);
        if (result <= 0) {
            throw new ServerErrorException("DB批量删除失败");
        }
        return result;
    }

    @Override
    public List<DirectionExcel> getExcelData() {
        return directionMapper.list(new DirectionPageDTO())
                .stream()
                .map(direction -> BeanUtil.copyProperties(direction, DirectionExcel.class))
                .collect(Collectors.toList());
    }
}
